package com.gcu.drivingschool.controller;

import cn.dev33.satoken.secure.BCrypt;
import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.gcu.drivingschool.common.enums.LoginType;
import com.gcu.drivingschool.domain.dto.PageBean;
import com.gcu.drivingschool.domain.dto.UpdateStudentDto;
import com.gcu.drivingschool.domain.po.Student;
import com.gcu.drivingschool.domain.vo.Result;
import com.gcu.drivingschool.service.StudentService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.enums.ParameterIn;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import java.util.Date;
import java.util.List;

/**
 * 学员控制器
 *
 * @author zzr
 * @create 2024-04-18-15:22
 */
@Tag(name = "学员控制器", description = "学员控制器")
@RestController
@RequiredArgsConstructor
@RequestMapping("/api/students")
public class StudentController {
    private final StudentService studentService;

    /**
     * 注册学员
     *
     * @param student
     * @return
     */
    @Operation(summary = "注册学员", description = "注册学员,手机号不可重复注册")
    @PostMapping("/add")
    public Result registerStudent(@RequestBody @Validated Student student) {
        student.setCreateTime(new Date());
        student.setPassword(BCrypt.hashpw(student.getPassword(), BCrypt.gensalt(12)));//密码加密
        try {
            studentService.save(student);
            return Result.success();
        } catch (DuplicateKeyException e) {
            return Result.fail("手机号已经注册");
        }
    }

    /**
     * 删除学员
     *
     * @param id
     * @return
     */
    @Parameter(name = "id", description = "学员id", in = ParameterIn.PATH, required = true)
    @Operation(summary = "删除学员", description = "删除学员")
    @DeleteMapping("/{id}")
    public Result delStudent(@PathVariable("id") Integer id) {
        boolean remove = studentService.removeById(id);
        if (!remove) {
            return Result.fail();
        }
        return Result.success();
    }

    /**
     * 获取学员信息列表
     *
     * @param pageNum
     * @param pageSize
     * @param telephone
     * @param name
     * @param id_number
     * @param age
     * @param sex
     * @return
     */
    @Parameters({
            @Parameter(name = "pageNum", description = "第几页", in = ParameterIn.QUERY),
            @Parameter(name = "pageSize", description = "每页条数", in = ParameterIn.QUERY),
            @Parameter(name = "id", description = "学员id", in = ParameterIn.QUERY),
            @Parameter(name = "telephone", description = "手机号", in = ParameterIn.QUERY),
            @Parameter(name = "name", description = "姓名", in = ParameterIn.QUERY),
            @Parameter(name = "id_number", description = "身份证号", in = ParameterIn.QUERY),
            @Parameter(name = "age", description = "年龄", in = ParameterIn.QUERY),
            @Parameter(name = "sex", description = "性别", in = ParameterIn.QUERY),
            @Parameter(name = "coachId", description = "教练id", in = ParameterIn.QUERY)
    })
    @Operation(summary = "获取学员信息列表", description = "填哪些参数代表根据这些参数查，哪些参数不填代表所有<br/>" +
            "自行组合...")
    @GetMapping
    public Result getStudentList(@RequestParam(required = false) Integer pageNum,
                                 @RequestParam(required = false) Integer pageSize,
                                 @RequestParam(required = false) Integer id,
                                 @RequestParam(required = false) String telephone,
                                 @RequestParam(required = false) String name,
                                 @RequestParam(required = false) String id_number,
                                 @RequestParam(required = false) Integer age,
                                 @RequestParam(required = false) String sex,
                                 @RequestParam(required = false) Integer coachId) {
        //如果不传pageNum和pageSize,不分页
        if (pageNum == null) {
            pageNum = 1;
        }
        if (pageSize == null) {
            pageSize = Integer.MAX_VALUE;
        }
        LambdaQueryWrapper<Student> wrapper = new LambdaQueryWrapper<>();
        wrapper
                .select(Student::getId,Student::getTelephone,Student::getName
                ,Student::getIdNumber,Student::getAge,Student::getSex,Student::getCoachId,Student::getCreateTime)
                .eq(id != null,Student::getId,id)
                .eq(StringUtils.isNotBlank(telephone), Student::getTelephone, telephone)
                .eq(StringUtils.isNotBlank(name), Student::getName, name)
                .eq(StringUtils.isNotBlank(id_number), Student::getIdNumber, id_number)
                .eq(age != null, Student::getAge, age)
                .eq(StringUtils.isNotBlank(sex), Student::getSex, sex)
                .eq(coachId != null, Student::getCoachId, coachId);
        PageHelper.startPage(pageNum, pageSize);//分页
        //查询数据
        List<Student> list = studentService.list(wrapper);
        Page p = (Page) list;
        PageBean pb = new PageBean(p.getTotal(), p.getResult());
        return Result.success(pb);
    }


    /**
     * 修改学员信息
     * @param student
     * @return
     */
    @Operation(summary = "修改学员信息", description = "填哪些参数代表根据这些参数改，哪些参数不填代表所有<br/>" +
            "自行组合...")
    @PutMapping
    public Result updateStudent(@RequestBody @Validated  UpdateStudentDto student) {
        Student s = studentService.getById(student.getId());
        if (s == null) {
            return Result.fail("学员不存在");
        }
        if (LoginType.STUDENT.getValue().equals(StpUtil.getSession().getType())) {
            if (student.getCoachId() != null) {//只允许学员报名一名教练
                //查询学员是否报名过教练
                if (s.getCoachId() != null) {
                    return Result.fail("学员已报名教练");
                }
            }
        }
        LambdaUpdateWrapper<Student> wrapper = new LambdaUpdateWrapper<>();
        wrapper.set(StringUtils.isNotBlank(student.getTelephone()), Student::getTelephone, student.getTelephone())
                .set(StringUtils.isNotBlank(student.getName()), Student::getName, student.getName())
                .set(StringUtils.isNotBlank(student.getIdNumber()), Student::getIdNumber, student.getIdNumber())
                .set(student.getAge() != null, Student::getAge, student.getAge())
                .set(StringUtils.isNotBlank(student.getSex()), Student::getSex, student.getSex())
                .set(StringUtils.isNotBlank(student.getPassword()), Student::getPassword,
                        BCrypt.hashpw(student.getPassword(),BCrypt.gensalt(12)))
                .set(student.getCoachId() != null, Student::getCoachId, student.getCoachId())
                .eq(Student::getId, student.getId());
        boolean update = studentService.update(wrapper);
        if (!update){
            return Result.fail();
        }
        return Result.success();
    }
}
